from rest_framework.serializers import ModelSerializer, SerializerMethodField
from school.models import Classes
from user.serializers import UserSerializer

class ClassesSerializer(ModelSerializer):
    # member = UserSerializer(many=True)
    # 这个方法可以调用这个序列化器上的某个方法返回的值。比如这里可以获取get_memberDetail返回的值
    member_detail = SerializerMethodField()

    class Meta:
        model = Classes
        exclude = ['is_delete']
        # extra_kwargs:给指定属性添加或者修改参数
        extra_kwargs = {'member': {'write_only': True}}  # 只写相当于只反序列化

    def get_member_detail(self, classes):  # get后面加上你要操作的字段，classes是班级模型类的实例化对象
        serializer = UserSerializer(classes.member.all(), many=True)
        # 分组：根据auth_group和auth_user_groups，老师组group_id是1，学生组group_id是2
        # 字段 'groups' 在django.contrib.auth.models.AnonymousUser['_groups']，用于管理正向查询用户所在的组
        data = {
            'teacher': [i for i in serializer.data if 1 in i['groups'] or i['is_superuser']],
            'student': [i for i in serializer.data if 2 in i['groups']],
        }
        return data
